package cn.dglydrpy.eshop.website.common.validate;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * 统一验证处理
 */
@Component  //交给spring管理
public class ValidateUtil implements InitializingBean {
    //校验器
    private Validator validator;
    @Override
    public void afterPropertiesSet() throws Exception {
        this.validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    //实现校验方法并返回校验结果
    public ValidationResult validate(Object bean){
        ValidationResult validationResult = new ValidationResult();
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(bean);
        if (constraintViolations.size()>0){
            //有错误信息
            validationResult.setHasError(true);
            constraintViolations.forEach(constraintViolation->{
                String errorMsg = constraintViolation.getMessage();
                String properyName = constraintViolation.getPropertyPath().toString();//错误字段
                validationResult.getErrorMsgMap().put(properyName,errorMsg);
            });
        }
        return validationResult;
    }
}
